package lockDemo.synchronizeDemo;

import java.util.concurrent.TimeUnit;

/**
 * @author jie
 * @version 创建时间：2017年12月6日 下午9:48:15
 * 思路是创建两个字符串a和b，再创建两个线程A和B，
 * 让每个线程都用synchronized锁住字符串（A先锁a，再去锁b；B先锁b，再锁a），
 * 如果A锁住a，B锁住b，A就没办法锁住b，B也没办法锁住a，这时就陷入了死锁。直接贴代码：
 */
public class DeadLock {
    public static String str1 = "str1";
    public static String str2 = "str2";

    public static void main(String[] args) {


        Thread a = new Thread(new Lock1());
        Thread b = new Thread(new Lock2());
        a.start();
        b.start();
    }
}

class Lock1 implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("lock1 running");
            while (true) {
                synchronized (DeadLock.str1) {
                    System.out.println("Lock1 lock str1");
                    TimeUnit.SECONDS.sleep(3);
                    synchronized (DeadLock.str2) {
                        System.out.println("Lock1 lock str2");
                    }
                }
            }
        } catch (Exception e) {
        }
    }
}

class Lock2 implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("lock2 running");
            while (true) {
                synchronized (DeadLock.str2) {
                    System.out.println("Lock2 lock str2");
                    TimeUnit.SECONDS.sleep(3);
                    synchronized (DeadLock.str1) {
                        System.out.println("Lock1 lock str1");
                    }
                }

            }
        } catch (Exception e) {
        }

    }
}

